const { saveUserInfo } = require('../../utils/user.js')
const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    studentId: '',
    password: '',
    showPassword: false,
    studentIdFocus: false,
    passwordFocus: false,
    showPasswordReset: false
  },

  // 添加页面加载时的检查
  onLoad() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      // 如果存在用户信息，直接跳转到首页
      wx.switchTab({
        url: '/pages/index/index'
      })
    }
  },

  // 输入事件处理
  onStudentIdInput(e) {
    this.setData({ studentId: e.detail.value })
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value })
  },

  // 焦点事件处理
  onStudentIdFocus() {
    this.setData({ studentIdFocus: true })
  },

  onStudentIdBlur() {
    this.setData({ studentIdFocus: false })
  },

  onPasswordFocus() {
    this.setData({ passwordFocus: true })
  },

  onPasswordBlur() {
    this.setData({ passwordFocus: false })
  },

  // 切换密码可见性
  togglePasswordVisibility() {
    this.setData({ showPassword: !this.data.showPassword })
  },

  // 登录
  onTapLogin() {
    const { studentId, password } = this.data

    // 验证表单
    if (!studentId) {
      wx.showToast({
        title: '请输入学号/工号',
        icon: 'none'
      })
      return
    }

    if (!password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }

    // 验证密码长度
    if (password.length < 6) {
      wx.showToast({
        title: '账号或密码错误',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '登录中...'
    })

    // 调用登录接口
    wx.request({
      url: getApiUrl('/user/login'),
      method: 'POST',
      data: {
        userAccount: studentId,
        userPassword: password
      },
      success: (res) => {
        wx.hideLoading()
        
        this.handleLoginSuccess(res)
      },
      fail: (error) => {
        console.error('Login failed:', error)
        wx.hideLoading()
        wx.showToast({
          title: '登录失败，请检查网络后重试',
          icon: 'none'
        })
      }
    })
  },

  // 在登录成功的回调中处理用户信息
  handleLoginSuccess(res) {
    if (res.data.code === 200) {
      const userData = res.data.data
      // 构造用户信息对象
      const userInfo = {
        id: userData.id,
        studentId: userData.userAccount,
        nickname: userData.username || '未设置昵称',
        avatar: userData.avatar || '/images/avatar/default.png',
        phone: userData.phone,
        gender: userData.gender,
        email: userData.email,
        userRole: userData.userRole,
        userStatus: userData.userStatus,
        biography: userData.biography,
        tags: userData.tags || [],
        createTime: userData.createTime,
        updateTime: userData.updateTime
      }
      
      // 保存到本地存储和全局数据
      wx.setStorageSync('userInfo', userInfo)
      getApp().globalData.userInfo = userInfo
      
      // 显示登录成功提示
      wx.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            })
          }, 1500)
        }
      })
    } else {
      wx.showToast({
        title: res.data.message || '登录失败',
        icon: 'none'
      })
    }
  },

  // 跳转到注册页面
  onTapRegister() {
    wx.redirectTo({
      url: '/pages/register/register',
      animationType: 'slide-in-right',
      duration: 300
    })
  },

  // 显示密码重置组件
  onTapForgetPassword() {
    this.setData({ 
      showPasswordReset: true 
    })
  },

  // 关闭密码重置组件
  onClosePasswordReset() {
    this.setData({ 
      showPasswordReset: false 
    })
  },

  // 密码重置成功回调
  onPasswordResetSuccess() {
    this.setData({ 
      showPasswordReset: false 
    })
    
    wx.showToast({
      title: '密码已重置，请登录',
      icon: 'success'
    })
  }
}) 